package officers;

import java.util.*;

public class Problem32_3 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> deque = new LinkedList<>();
        List<List<Integer>> lists = new ArrayList<>();
        if (root != null) deque.add(root);
        while (!deque.isEmpty()) {
            LinkedList<Integer> nodes = new LinkedList<>();
            for (int i = deque.size(); i > 0; i--) {
                TreeNode node = deque.poll();
                if (lists.size() % 2 == 0) nodes.addLast(node.val);
                else nodes.addFirst(node.val);
                if (node.left != null) deque.add(node.left);
                if (node.right != null) deque.add(node.right);
            }
            lists.add(nodes);
        }
        return lists;
    }
}
